import config from "../config/config";
import { AuthService } from "../services/auth_service";

const getToken = () => {
  return new Promise((resolve, reject) => {
    const app = getApp();
    const userInfo = app.globalData.userInfo;
    const tokenExpires = app.globalData.tokenExpires;
    if (userInfo && tokenExpires > Date.now()) {
      resolve(userInfo);
    } else {
      wx.login({
        success: (res) => {
          let authService = new AuthService();
          authService.login(res.code).then((res) => {
            app.globalData.userInfo = res.data;
            app.globalData.tokenExpires = Date.now() + 3600 * 24 * 3 * 1000;
            wx.setStorageSync(
              "tokenExpires",
              Date.now() + 3600 * 24 * 3 * 1000
            );
            wx.setStorageSync("userInfo", JSON.stringify(res.data));
            resolve(res.data);
          });
        },
      });
    }
  });
};

class HTTP {
  base_url = config.baseUrl;

  static _isHttp(url) {
    return url.substr(0, 4).toLowerCase() === "http";
  }

  async _request({
    url,
    data = {},
    config,
    method,
    headers = {
      "content-type": "application/json",
    },
    needAuth = true,
  }) {
    var token;
    var userId;
    if (needAuth) {
      var userInfo = await getToken();
      token = 'Bearer ' + userInfo.token;
      userId = userInfo.id;
      Object.assign(data, {
        userId,
      });
    }
    const is_http = HTTP._isHttp(url);
    // restful 处理
    Object.keys(data).forEach((key) => {
      if (url.indexOf(`:${key}`) !== -1) {
        url = url.replace(`:${key}`, data[key]);
        delete data[key];
      }
    });

    return new Promise((resolve, reject) => {
      wx.request({
        url: is_http ? url : this.base_url + url,
        header: Object.assign(headers, {
          Authorization: token || ""
        }),
        method,
        data,
        ...config,
        success: (result) => {
          if (result.data.statusCode !== 200) {
            wx.showToast({
              title: result.data.message,
              icon: "error",
            });
          }
          resolve(result.data);
        },
        fail: (res) => {
          wx.showToast({
            title: res.data.message,
            icon: "error",
          });
          reject(res);
        },
      });
    });
  }

  get({url, data, needAuth=true, config}) {
    console.log(url + ' ' + needAuth);
    return this._request({
      url,
      data,
      config,
      method: "GET",
      needAuth,
    });
  }

  post({url, data, needAuth = true, config}) {
    return this._request({
      url,
      data,
      config,
      method: "POST",
      needAuth,
    });
  }

  put({url, data, config}) {
    return this._request({
      url,
      data,
      config,
      method: "PUT",
    });
  }

  patch({url, data, config}) {
    return this._request({
      url,
      data,
      config,
      method: "PATCH",
    });
  }
}

export { HTTP };
